package alp.starcode.nudtportal.framework.listener;

import alp.starcode.common.dict.model.DictData;
import alp.starcode.common.dict.template.DictTemplate;
import alp.starcode.nudtportal.framework.base.BaseService;
import alp.starcode.nudtportal.framework.constant.ExchangeEnum;
import alp.starcode.nudtportal.framework.constant.ProjectConst;
import alp.starcode.nudtportal.framework.listener.model.TransmissionModel;
import alp.starcode.nudtportal.framework.mybatis.dao.EasytongAccountInfoDao;
import alp.starcode.nudtportal.framework.mybatis.dao.impl.UserAccountDaoImpl;
import alp.starcode.nudtportal.framework.mybatis.dao.impl.UserServiceDaoImpl;
import alp.starcode.nudtportal.framework.mybatis.entity.EasytongAccountInfo;
import alp.starcode.nudtportal.framework.mybatis.entity.UserAccount;
import alp.starcode.nudtportal.framework.mybatis.entity.UserService;
import alp.starcode.nudtportal.framework.util.MQUtils;
import alp.starcode.nudtportal.framework.util.SM2Utils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * @program: nudt-portal
 * @description: 监听邮箱服务mq消息
 * @author: cy
 * @create: 2023-09-15 11:17
 **/
@Slf4j
@Component
public class UserServiceListener extends BaseService {
    @Autowired
    private MQUtils mqUtils;

    @Value("${mq.SM2.privateKey}")
    public String privateKey;

    @Autowired
    private UserAccountDaoImpl userAccountDao;

    @Autowired
    private DictTemplate dictTemplate;

    @Autowired
    private UserServiceDaoImpl userServiceDao;

    @Autowired
    private EasytongAccountInfoDao easytongAccountInfoDao;

    @RabbitListener(queues = "${mq.receiveQueueName}")
    public void receiveMessage(String msg) {
        TransmissionModel transmissionModel = new TransmissionModel();
        Boolean flag = false;
        try {
            transmissionModel = JSON.parseObject(msg, TransmissionModel.class);
            LambdaQueryWrapper<EasytongAccountInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EasytongAccountInfo::getUserId,getCurrentUser().getUserId());
            EasytongAccountInfo easytongAccountInfo = easytongAccountInfoDao.getOne(wrapper);
            String data = SM2Utils.decrypt(privateKey, transmissionModel.getContent());
            // 处理消息的业务逻辑
            flag = processMessage(data);
            mqUtils.addLogExchange(getCurrentUser(), ExchangeEnum.TYPE_EMAIL_ACTIVE.getName(), data, flag, System.currentTimeMillis());
        } catch (Exception e) {
            // 处理错误并进行消息拒绝
            handleExceptionAndReject(transmissionModel, e,flag);
        }
    }

    /**
     * 处理业务逻辑
     * @param data
     */
    private Boolean processMessage(String data) throws Exception {
        //解析并添加用户邮箱服务
        Map map = JSON.parseObject(data, HashMap.class);
        String camupsNumber = String.valueOf(map.get("camupsNumber"));
        String emailAccount = String.valueOf(map.get("emailAccount"));

        //查询用户信息
        UserAccount userAccount = userAccountDao.getOne(new LambdaQueryWrapper<UserAccount>()
                .eq(UserAccount::getIsDeleted, ProjectConst.IS_DELETED_N).eq(UserAccount::getCampusNumber, camupsNumber));

        //用户不存在就不需要执行下面业务
        if(userAccount != null){
            DictData dictData = dictTemplate.getDictDataByDictLabel(ProjectConst.M_EMAIL);
            //查询是否有对应的邮箱服务
            UserService emailService = userServiceDao.getOne(new LambdaQueryWrapper<UserService>().eq(UserService::getUserId, userAccount.getUserId())
                    .eq(UserService::getServiceCode, dictData.getDictValue()));

            if(emailService != null){
                emailService.setUpdateTime(System.currentTimeMillis()).setDataSource(ProjectConst.ADD_USER_TYPE_NW).setServiceAccount(emailAccount);
            }else{
                //添加用户服务
                UserService service = new UserService();
                service.setServiceId(UUID.randomUUID().toString()).setUserId(userAccount.getUserId())
                        .setServiceAccount(emailAccount).setCreateTime(System.currentTimeMillis()).setServiceStatus(ProjectConst.IS_DELETED_N)
                        .setServiceName(dictData.getDictRemark()).setServiceCode(dictData.getDictValue()).setUpdateTime(System.currentTimeMillis())
                        .setDataSource(ProjectConst.ADD_USER_TYPE_NW);
                service.insertOrUpdate();
            }
            return true;
        }
        return false;
    }

    /**
     * 记录消费信息
     * @param messageEntity
     * @param e
     */
    private void handleExceptionAndReject(TransmissionModel messageEntity, Exception e,Boolean flag) {
        // 处理错误，可以记录日志
        log.error("Error processing message: " + e.getMessage());
        mqUtils.addLogExchange(getCurrentUser(), ExchangeEnum.TYPE_EMAIL_ACTIVE.getName(), messageEntity.toString(), flag, System.currentTimeMillis());
        // 拒绝消息，第二个参数表示是否重新入队（false表示不重新入队）
        throw new AmqpRejectAndDontRequeueException(e.getMessage());
    }
}
